package com.freight.core.common.aop;


import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.servlet.ServletUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Description: 记录入参出参方法
 * @Param:
 * @return:
 **/
@Aspect
@Component
@Slf4j
public class MethodAop {


    @Pointcut("execution(public * com.freight.*.service.*.*(..))")
    public void getMethodName() {

    }

    @Pointcut("execution(* com.freight.*.service.*.*(..))")
    public void printParams() {

    }

    /**
     * 打印请求参数
     *
     * @param joinPoint
     */
    @Before(value = "printParams()")
    public void paramsLog(JoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        // 内部调用有问题
        if(requestAttributes != null ) {
            HttpServletRequest request = requestAttributes.getRequest();
            Class<?> targetClass = joinPoint.getTarget().getClass();
            if (targetClass.isAnnotationPresent(Api.class)) {
                Api swaggerApi = (Api) targetClass.getDeclaredAnnotation(Api.class);
                log.info("模块的中文汉字 {} , {}", swaggerApi.value(), swaggerApi.tags()[0]);
            }
            log.info("sign -- {}", joinPoint.getSignature());
            log.info("请求地址:" + request.getRequestURL().toString());
            log.info("请求方式:" + request.getMethod());
            Map<String, String> m = ServletUtil.getParamMap(request);
            log.info("请求参数：{}", m);
        }
    }

    /**
     * 打印响应内容
     *
     * @param o
     */
//    @AfterReturning(returning = "o", pointcut = "printParams()")
//    public void methodAfterReturing(Object o) {
////        log.info("返回的结果为: " + JSONUtil.parse(o).toStringPretty());
////        log.info("返回的结果为: " + o.toString());
//    }


    /**
     * 打印方法耗时
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("printParams()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = DateUtil.current(false);
        log.info("执行方法：{},开始时间:{}", joinPoint.getSignature().getName(), startTime);
        Object result = joinPoint.proceed();
        long endTime = DateUtil.current(false);
        log.info("执行方法：{}，结束时间:{} , 用时:{} 毫秒 , ", joinPoint.getSignature().getName(), endTime, endTime - startTime);
        return result;
    }


}